package com.szzg10.webservice.chapter3;

import java.awt.Image;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import javax.jws.WebMethod;
import javax.jws.WebService;

@WebService
public class SkiImageService {

	private static final String[] names = {"1.jpg", "2.jpg", "3.jpg"};
	
	@WebMethod
	public Image getImage(String name) {
		return createImage(name);
	}
	
	@WebMethod
	public List<Image> getImages() {
		
		List<Image> list = new ArrayList<Image>();
		for(String name: names) {
			list.add(getImage(name));
		}
		
		return list;
	}
	
	private Image createImage(String name) {
		
		byte[] bytes = getRawBytes(name);
		ByteArrayInputStream in = new ByteArrayInputStream(bytes);
		
		Iterator<ImageReader> iterator = ImageIO.getImageReadersByFormatName("jpg");
		ImageReader reader = iterator.next();
		
		try {
			ImageInputStream imageInputStream = ImageIO.createImageInputStream(in);
			reader.setInput(imageInputStream, true);
			
			return reader.read(0);
		} catch (IOException e) {
			e.printStackTrace();
			
			return null;
		}
		
	}
	
	private byte[] getRawBytes(String name) {
		
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		
		String fileName = this.getClass().getResource("").getPath() + "img/" + name;
		try {
			FileInputStream in = new FileInputStream(new File(fileName));
			byte[] buffer = new byte[2048];
			
			int n = 0;
			while((n = in.read(buffer)) != -1) {
				out.write(buffer, 0, n);
			}
			
			out.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return out.toByteArray();
	}
}
